package edu.biwu.dao.impl;

import edu.biwu.dao.ProductDao;
import edu.biwu.mapper.ProductMapper;
import edu.biwu.po.Product;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
@Setter
@Repository
public class ProductDaoImpl implements ProductDao {
    //通过setter方法在spring中注入QueryRunner对象


//   例如: public QueryRunner getQueryRunner() {
//        return queryRunner;
//    }
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public List<Product> findAll() {
       /* try {
            return queryRunner.query("SELECT * FROM spring.product",new BeanListHandler<Product>(Product.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }*/
        return jdbcTemplate.query("SELECT * FROM spring.product", productMapper);
    }

    @Override
    public Product findById(int pid) {
        return jdbcTemplate.queryForObject("SELECT * FROM spring.product WHERE pid=?", productMapper, pid);
    }
    @Override
    public void updateProduct(Product product) {

        jdbcTemplate.update("UPDATE spring.product SET pname=?,price=?,category=? WHERE pid=?", product.getPname(),
                product.getPrice(), product.getCategory(), product.getPid());
//        int i = 1/0;
    }

    @Override
    public void deleteProduct(int pid) {
        jdbcTemplate.update("DELETE FROM spring.product WHERE pid=?", pid);
    }



    @Override
    public void saveProduct(Product product) {
        jdbcTemplate.update("INSERT INTO spring.product(pname,price,category) values(?,?,?)",product.getPname(),product.getPrice(),product.getCategory());
    }
}
